package com.azkj.album.view.activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.azkj.album.BuildConfig;
import com.azkj.album.R;
import com.azkj.album.dto.LoginBean;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.network.ConfigStorage;
import com.azkj.album.network.Constants;
import com.azkj.album.network.networkframe.net.HttpsUtil;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.presenter.LoginPresenter;
import com.azkj.album.presenter.SendSmsPresenter;
import com.azkj.album.utils.InputFilterUtils;
import com.azkj.album.utils.StatusBarUtil;
import com.azkj.album.view.base.BaseActivity;
import com.azkj.album.view.iview.ILoginView;
import com.azkj.album.view.iview.ISmsView;
import com.azkj.album.view.widgets.MyTextWatcher;
import com.azkj.album.view.widgets.dialog.CommonDialog;
import com.azkj.album.view.widgets.dialog.ProtocolDialog;
import com.bytedance.sdk.open.douyin.DouYinOpenApiFactory;
import com.bytedance.sdk.open.douyin.DouYinOpenConfig;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity implements ILoginView, ISmsView {

    @BindView(R.id.login_phone)
    EditText mEtPhone;
    @BindView(R.id.et_login_psd)
    EditText mEtPsd;
    @BindView(R.id.et_login_code)
    EditText mEtCode;

    @BindView(R.id.login_user)
    Button mBtnLogin;


    @BindView(R.id.tv_login_psd_visibility)
    ImageView mIvSee;

    @BindView(R.id.iv_check)
    ImageView mIvCheck;

    @BindView(R.id.tv_send_code)
    TextView mTvSend;
    @BindView(R.id.tv_version)
    TextView mTvVersion;

    @BindView(R.id.ll_login_psd)
    LinearLayout mLlPsd;

    @BindView(R.id.ll_login_sms)
    LinearLayout mLlSms;

    boolean isChecked = false;
    private int mLoginType = 0;//0:密码，1：验证码

    private LoginPresenter mPresenter;
    private SendSmsPresenter sendSmsPresenter;
    private IWXAPI api;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.immersive(this);
        EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_LOGIN_START, null));
        mTvVersion.setText("版本：V" + BuildConfig.VERSION_NAME);

//        mEtPhone.setText("18010167520");
//        mEtPsd.setText("111111");
//        isChecked = true;
//        mIvCheck.setImageResource(isChecked ? R.mipmap.ic_checked : R.mipmap.ic_uncheck);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        if (isNeedProtocolDialog()) {
            showProtocolDialog();
        } else {
            api = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID, true);
            api.registerApp(Constants.WX_APP_ID);
        }
        mEtPhone.setFilters(new InputFilter[]{InputFilterUtils.getNoSpaceFilter()});
        mEtCode.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                findViewById(R.id.iv_login_code_clear).setVisibility(
                        TextUtils.isEmpty(s.toString()) ? View.GONE : View.VISIBLE
                );

                if (TextUtils.isEmpty(s)) {
                    mBtnLogin.setEnabled(false);
                } else if (mLoginType == 1) {
                    mBtnLogin.setEnabled(!TextUtils.isEmpty(mEtCode.getText()));
                }

            }
        });

        mEtPhone.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s)) {
                    mBtnLogin.setEnabled(false);
                } else if (mLoginType == 0) {
                    mBtnLogin.setEnabled(!TextUtils.isEmpty(mEtPsd.getText()));
                } else {
                    mBtnLogin.setEnabled(!TextUtils.isEmpty(mEtCode.getText()));
                }
            }
        });
        mEtPsd.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s)) {
                    mBtnLogin.setEnabled(false);
                } else if (mLoginType == 0) {
                    mBtnLogin.setEnabled(!TextUtils.isEmpty(mEtPhone.getText()));
                }
            }
        });


    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.tv_login_psd_visibility, R.id.forget_pwd, R.id.login_user,
            R.id.tv_register, R.id.tv_help, R.id.login_wx, R.id.tv_send_code, R.id.login_psd, R.id.login_sms, R.id.iv_login_code_clear,
            R.id.iv_check, R.id.tv_xieyi1, R.id.tv_xieyi2, R.id.tv_wx_code})
    public void onClick(View v) {
//        if (Utils.isFastClick()) return;
        Intent intent;
        switch (v.getId()) {
            case R.id.tv_login_psd_visibility:
                if (mEtPsd.getTransformationMethod() == HideReturnsTransformationMethod
                        .getInstance()) {
                    mEtPsd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mIvSee.setImageResource(R.mipmap.icon_login_eye);
                } else {
                    mEtPsd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());  //密码以明文显示}
                    mIvSee.setImageResource(R.mipmap.icon_login_eye_open);
                }
                if (!TextUtils.isEmpty(mEtPsd.getText()))
                    mEtPsd.setSelection(mEtPsd.getText().length());
                break;
            case R.id.forget_pwd:
                RegisterActivity.startActivity(this, 2, null);
                break;
            case R.id.login_user:
                loginUser();
                break;
            case R.id.tv_register:
                RegisterActivity.startActivity(this, 0, null);
                break;
            case R.id.tv_help:
                intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("title", "使用说明");
                intent.putExtra("url", Constants.WEB_PAGE_INSTRUCTIONS);
                startActivity(intent);
                break;
            case R.id.login_wx:
                loginWx();
                break;
            case R.id.iv_check:
                isChecked = !isChecked;
                mIvCheck.setImageResource(isChecked ? R.mipmap.ic_checked : R.mipmap.ic_uncheck);
                break;
            case R.id.tv_xieyi1:
                intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("title", "隐私政策");
                intent.putExtra("url", Constants.WEB_PAGE_PROTOCOL_1);
                startActivity(intent);
                break;
            case R.id.tv_xieyi2:
                intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("title", "用户协议");
                intent.putExtra("url", Constants.WEB_PAGE_PROTOCOL_2);
                startActivity(intent);
                break;
            case R.id.login_psd:
                if (mLoginType == 0) return;
                loginPsdOrSms(0);
                break;
            case R.id.login_sms:
                if (mLoginType == 1) return;
                loginPsdOrSms(1);
                break;
            case R.id.tv_send_code:
                sendSMS();
                break;
            case R.id.iv_login_code_clear:
                mEtCode.setText("");
                break;
            case R.id.tv_wx_code:
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText("baopan2333");
                ToastUtils.showCenterToast("已复制！");
                break;
        }
    }

    private void loginPsdOrSms(int type) {
        mLoginType = type;
        mLlPsd.setVisibility(mLoginType == 0 ? View.VISIBLE : View.GONE);
        mLlSms.setVisibility(mLoginType == 1 ? View.VISIBLE : View.GONE);
        mEtPhone.setText("");
        mEtPsd.setText("");
        mEtCode.setText("");
        findViewById(R.id.iv_login_code_clear).setVisibility(View.GONE);
        mBtnLogin.setEnabled(false);
    }

    private void loginWx() {
        if (!isChecked) {
            ToastUtils.showCenterToast("请阅读并同意《隐私政策》及《用户协议》");
            return;
        }
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        api.sendReq(req);
    }

    private void loginUser() {
        if (!isChecked) {
            ToastUtils.showCenterToast("请阅读并同意《隐私政策》及《用户协议》");
            return;
        }
        if (TextUtils.isEmpty(mEtPhone.getText().toString().trim())) {
            ToastUtils.showCenterToast("请输入手机号");
            return;
        }
        Map<String, Object> map = HttpsUtil.getCommonPostRequest();
        if (mLoginType == 0) {
            if (TextUtils.isEmpty(mEtPsd.getText().toString().trim())) {
                ToastUtils.showCenterToast("请输入密码");
                return;
            }
            map.put("account", mEtPhone.getText().toString().trim());
            map.put("password", mEtPsd.getText().toString().trim());
            mPresenter.login(map);
        } else {
            if (TextUtils.isEmpty(mEtCode.getText().toString().trim())) {
                ToastUtils.showCenterToast("请输入验证码");
                return;
            }
            map.put("mobile", mEtPhone.getText().toString().trim());
            map.put("captcha", mEtCode.getText().toString().trim());
            mPresenter.loginSms(map);
        }
    }

    @Override
    protected void initPresenter() {
        mPresenter = new LoginPresenter(this);
        sendSmsPresenter = new SendSmsPresenter(this);
    }


    @Subscribe
    public void onMessage(MessageEvent messageEvent) {
        super.onMessage(messageEvent);
        switch (messageEvent.getType()) {
            case MessageType.TYPE_ON_WX_CODE_RESULT:
                mPresenter.getWxOpenID(messageEvent.getMsg());
                break;

        }

    }


    @Override
    public void loginSuccess(boolean isVisitor, LoginBean loginBean) {
        ToastUtils.showCenterToast("登录成功");
        if (isVisitor) {
            ConfigStorage.getInstance().saveVisitorBean(loginBean);
        } else {
            ConfigStorage.getInstance().saveUserBean(loginBean);
        }
        Intent intent = new Intent(this, HomeActivity.class);
        EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_LOGIN_SUCCESS));
        startActivity(intent);

    }

    @Override
    public void loginFail(String error) {
        ToastUtils.showCenterToast(error);
        if ("请绑定手机号".equals(error)) {
            Intent intent = new Intent(this, BindPhoneActivity.class);
            intent.putExtra("type", 0);
            intent.putExtra("unionid", mPresenter.getUnionid());
            intent.putExtra("wx_username", mPresenter.getWx_username());
            startActivity(intent);
        }
    }


    private boolean isNeedProtocolDialog() {
        return !mSharedPreferences.getBoolean("isCheckedProtocol", false);
    }

    private void showProtocolDialog() {

        new ProtocolDialog.Builder(this).setCallback(agree -> {
            if (agree) {
                mSharedPreferences.edit().putBoolean("isCheckedProtocol", true).apply();
                init3rdSDK();

            } else {
                finish();
            }
        }).show();

    }

    private void init3rdSDK() {

        api = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID, true);
        api.registerApp(Constants.WX_APP_ID);
        mSharedPreferences.edit().putBoolean("is_first", true).apply();
        if (BuildConfig.BUILD_TYPE.equals("release")) {
            UMConfigure.init(LoginActivity.this, Constants.UMENG_KEY, Constants.UMENG_CHANNEL, UMConfigure.DEVICE_TYPE_PHONE, "");
            MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
            DouYinOpenApiFactory.init(new DouYinOpenConfig(Constants.DOU_YIN));
        }
    }

    @Override
    public void sendSmsSuccess(TextView textView) {
        ToastUtils.showCenterToast("验证码已发送，请注意查收");
        startTimer();
    }

    @Override
    public void sendSmsFail(String msg) {
        ToastUtils.showCenterToast(msg);
    }

    private void sendSMS() {

        if (TextUtils.isEmpty(mEtPhone.getText().toString().trim())) {
            ToastUtils.showCenterToast("请输入手机号");
            return;
        }

        Map<String, Object> map = HttpsUtil.getCommonPostRequest();
        map.put("mobile", mEtPhone.getText().toString().trim());
        String event = "mobilelogin";
        map.put("event", event);
        sendSmsPresenter.sendSMS(map);
    }

    //开启倒计时
    private void startTimer() {
        final Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            private int counter = 60;

            public void run() {

                runOnUiThread(() -> {
                    if (counter > 0) {
                        mTvSend.setText(String.format("%ds后重新发送", counter));
                    } else {
                        mTvSend.setText("发送验证码");
                        mTvSend.setEnabled(true);
                        mTvSend.setTextColor(getResources().getColor(R.color.color_blue));
                        timer.cancel();
                    }

                    counter--;
                });
            }
        };
        timer.schedule(task, 0L, 1000L);
        mTvSend.setEnabled(false);
        mTvSend.setTextColor(getResources().getColor(R.color.color_99));
    }

    private void showError(String error) {

        new CommonDialog.Builder(this).setDesc(error)
                .setBackground(R.mipmap.ic_login_error).
                setButton(null, "我知道了").
                setOnClickListener((dialog, confirm) -> dialog.dismiss()).show();

    }

    @Override
    public void checkSmsSuccess() {

    }

    @Override
    public void checkSmsFail(String msg) {

    }
}
